import webapp2
import app_main

class AppHandler(webapp2.RequestHandler):
    """ Base handler with jinja environment included """
    def __init__(self, request, response):
        """ init self.jinja """
        super(AppHandler, self).__init__(request, response)
        self.jinja = app_main.JINJA_ENVIRONMENT

    def render_str(self, template_name, render_dict = None, **kargs):
        """ Render jinja template and return str """
        template = self.jinja.get_template(template_name)
        return template.render(render_dict or kargs)

    def render_write(self,template_name, render_dict=None, **kargs):
        """ Render template to the outstream response.write """
        self.response.write(self.render_str(template_name, render_dict or kargs))

    def get_ndb_ent_by_id(self,model,_id,**kargs):
        """ Return entity from ndb by id.
            If there are no such? through 404 page
        """
        try:
            ent = model.get_by_id(int(_id), **kargs)
        except ValueError:
            ent = model.get_by_id(_id, **kargs)
        # If there is no such id then redirect to 404 page
        if ent == None:
            self.abort(404)
        return ent

    def get_ndb_ent_by_name(self,model,name,ancestor=None):
        """ Return entity from ndb by Name
        """
        try:
            ent = model.query(ancestor=ancestor).filter(model.name == name).fetch(1)[0]
        except IndexError:
            self.abort(404)
        return ent

    def put_unique_ndb_ent(self, model, name, ancestor=None):
        """ Put new unique ndb entity
        """
        new_ent = None
        if not model.query().filter(model.name==name).fetch():
            new_ent = model(name=name, parent=ancestor)
            new_ent.put()
        return new_ent

    def check_ndb_ent(self, model, new_name, ancestor=None):
        """ Check if new_name had been used in another entity
        """
        try:
            self.get_ndb_ent_by_name(model, new_name, ancestor)
            return False
        except webapp2.HTTPException:
            return True




